package studio.raptor.extractor.segment.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Repository;
import studio.raptor.extractor.common.util.JdbcUtils;
import studio.raptor.extractor.segment.entity.EventNode;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuyong8 on 2017/7/28.
 */
@Repository
public class EventNodeDao {
    private static final Logger log = LoggerFactory.getLogger(EventNodeDao.class);
    private static String QUERY_EVENT_NODE = "SELECT event_kind_id,node_name,server_url FROM databus.event_node_server WHERE event_kind_id = ?";

    @Autowired
    @Qualifier("extractorDataSource")
    private DataSource dataSource;

    public List<EventNode> queryEventNodesByKindId(Integer kindId) throws Exception{
        Connection connection = null;
        PreparedStatement pstmt = null;
        List<EventNode> eventNodes = new ArrayList<EventNode>();
        String sql = QUERY_EVENT_NODE;
        try {
            connection = dataSource.getConnection();
            pstmt = connection.prepareStatement(sql);
            pstmt.setInt(1, kindId);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                EventNode eventNode = new EventNode();
                eventNode.setKindId(rs.getInt("event_kind_id"));
                eventNode.setNodeName(rs.getString("node_name"));
                eventNode.setServerUrl(rs.getString("server_url"));
                eventNodes.add(eventNode);
            }
        } catch (Exception e) {
            log.error("query event meta by kindId and status failed", e);
            throw e;
        } finally {
            JdbcUtils.close(pstmt);
            JdbcUtils.close(connection);
        }
        return eventNodes;
    }
}
